import React, { Component } from 'react';
import { Image, View, Dimensions, StyleSheet, Platform, WebView, ScrollView, Alert,DeviceEventEmitter } from 'react-native';
import Echarts from 'native-echarts';
import STRING from '../../const_string_zh_CN';
import URL from '../../net/url.js';
import { NavigationActions } from 'react-navigation'
import { connect } from 'react-redux';
import interaction from '../../net/interaction.js';
import { Container, Thumbnail, Text, Button, Icon, Body, List, ListItem, Content, Spinner } from 'native-base';
const { width, height } = Dimensions.get('window');
const marginTop = Platform.OS === 'ios' ? 20 : 0;
class question_teacher extends Component {
    static navigationOptions = ({ navigation }) => ({
        title: navigation.state.params.title,
    });
    //js组件的构造函数，js的生命周期
    constructor(props) {
        super(props);
        //state内部维护的一个状态，我们刚开始进来的为空，来加载空的view
        this.state = {
            content: null,
            correctAnswer: '无',
            optionTitle: null,
            optionNum:null,
            questionStatus: 'close',
            questionButton: '发布题目',
        };
    }
    render() {
        const { subject } = this.props;
        const { subject_course } = this.props;
        let subjectId;
        let subjectTitle;
        let subjectType;
        if (this.props.navigation.state.params.type == 'course') {
            subjectTitle = subject_course.subjectTitle;
            subjectType = subject_course.subjectType;
        }
        else {
            subjectTitle = subject.subjectTitle;
            subjectType = subject.subjectType;
        }
        const { navigate } = this.props.navigation;
        var startTime = new Date();
        const option = {
            title: {
                text: '答题详情'
            },
            //点击某一个点的数据的时候，显示出悬浮窗
            tooltip: {
                trigger: 'axis'
            },
            //各种表格
            toolbox: {
                //改变icon的布局朝向
                orient: 'vertical',
                show: true,
                showTitle: true,
            },
            xAxis: [
                {
                    //就是一月份这个显示为一个线段，而不是数轴那种一个点点
                    boundaryGap: true,
                    type: 'category',
                    name: '选项',
                    data: this.state.optionTitle,
                }
            ],
            yAxis: [
                {
                    type: 'value',
                    name: '人数'
                }
            ],
            //图形的颜色组
            color: ['#158B71'],
            //需要显示的图形名称，类型，以及数据设置
            series: [
                {
                    name: '人数',
                    //默认显
                    type: 'bar',
                    data: this.state.optionNum,
                },]
        };
        if (!this.state.content) {
            return this.renderLoadingView();
        }
        if (this.state.questionStatus == 'close') {
            return (
                <ScrollView ref={(scrollView) => { _scrollView = scrollView; }}>
                    <Content style={StyleSheet.flatten(styles.Content)}>
                        {this.renderContent()}
                    </Content>
                </ScrollView>

            );
        }
        return (
            <ScrollView ref={(scrollView) => { _scrollView = scrollView; }}>
                <Content style={StyleSheet.flatten(styles.Content)}>
                    {this.renderContent()}
                    <List>
                        <Echarts option={option} height={300} width={width} />
                    </List>
                </Content>
            </ScrollView>

        );
    }
    //加载等待的view
    renderLoadingView() {
        return (
            <Container>
                <Content>
                    <Spinner color='green' />
                </Content>
            </Container>
        );
    }
    //加载题目内容
    renderContent() {
        return (
            <View>
                <View style={StyleSheet.flatten(styles.view)} >
                    <ListItem button  >
                        <Icon name='ios-paper-outline' style={{color:'#28AB91'}}/>
                        <Body>
                            <Text style={StyleSheet.flatten(styles.text_style)}>{this.state.content[0].stemInfo}</Text>
                        </Body>
                    </ListItem>
                    <List dataArray={this.state.content}
                        renderRow={(item) =>
                            <ListItem style={StyleSheet.flatten(styles.ListItem)}>
                                <Text>{item.optionTitle}:</Text>
                                <Text style={{ marginLeft: 10 }}>{item.optionContent}</Text>
                            </ListItem>
                        } >
                    </List>
                </View>
                <View style={StyleSheet.flatten(styles.flexbox)}>
                    <Text style={StyleSheet.flatten(styles.text_style)}>题目类型：{this.state.content[0].subjectType}</Text>
                    <Text style={StyleSheet.flatten(styles.text_style)}>答案详情：{this.state.correctAnswer}</Text>
                </View>
                <List  >
                    <ListItem itemDivider style={StyleSheet.flatten(styles.flexbox)}>
                        {/*<Button block light style={StyleSheet.flatten(styles.button_default)} >
                                <Text onPress={() => { this.fetch_getSubjectStatistic() }} >答题结果</Text>
                            </Button>*/}
                        {/*<Button block light style={StyleSheet.flatten(styles.button_default)} >
                                <Text>关闭答题</Text>
                            </Button>*/}
                        <Button block light style={StyleSheet.flatten(styles.button_default)} onPress={() => { this.questionButton_onPress() }}>
                            <Text style={{color:'#fff'}}>{this.state.questionButton}</Text>
                        </Button>
                        <Button block light style={StyleSheet.flatten(styles.button_default)}
                            onPress={() => {
                                this.publicRightAnswer();
                            }}>
                            <Text style={{color:'#fff'}}>公布答案</Text>
                        </Button>
                        {/*<Button block light style={StyleSheet.flatten(styles.button_default)}
                            onPress={() => {
                                this.publicRightAnswer();
                            }}>
                            <Text>答题详情</Text>
                        </Button>*/}
                    </ListItem>
                </List>
            </View>
        );
    }
    async  componentWillMount() {
        //判断题目提送状态呈现对应图标（开启题目&结束答题）
        const { InteractionCourseId_OnlineClassID } = this.props;
        const { subject } = this.props;
        const { subject_course } = this.props;
        // const { GetSendSubjectID } = this.props;

        let subjectId;
        if (this.props.navigation.state.params.type == 'course') {
            console.log('课程-交互');
            subjectId = subject_course.subjectId;
        }
        else {
            console.log('发现-交互');
            subjectId = subject.subjectId;
        }
        let Interaction = new interaction();
        //判断开启题目&结束答案图标的呈现
        console.log('测试redux');
        console.log(InteractionCourseId_OnlineClassID);
        let PushSubject = await Interaction.CheckPushSubjectIcon(InteractionCourseId_OnlineClassID.OnlineClassID, subjectId);
        if (PushSubject.errorCode == 0) {
            const { GetSendSubjectID } = this.props;
            this.setState({ questionStatus: 'open' });
            this.setState({ questionButton: '结束答题' });
             console.log('GetSendSubjectID.SendSubjectID' + GetSendSubjectID.SendSubjectID);
            //定时拉取答题结果 SendSubjectID  
            this.timer = setInterval(() => { this.fetch_getSubjectStatistic(); }, 5000);
        }
        //通过题目id获取题目详情
        let SubjectInfo = await Interaction.getSubjectInfo(subjectId);
        this.setState({
            content: SubjectInfo,
        });
        //获取正确答案
        let correctAnswer = await Interaction.getSubjectAnswer(subjectId);
        this.setState({
            correctAnswer: correctAnswer,
        });
    }
    componentWillUnmount() {
        this.timer && clearInterval(this.timer);
    }
    //发布题目，关闭答题按钮的单击事件
    async questionButton_onPress() {
        let Interaction = new interaction();
        const { course_info } = this.props;
        const { InteractionCourseId_OnlineClassID } = this.props;
        const { subject_course } = this.props;
        const { PushSendSubjectID } = this.props;
        console.log('教师名' + course_info.chiefTeacherName);
        if (this.state.questionButton == '发布题目') {
           let message=[{subjectId:subject_course.subjectId,menu_id:subject_course.menu_id}] 
             DeviceEventEmitter.emit('pushing_icon_color', message);
            let PushTopicResult = await Interaction.PushTopic(subject_course.subjectId, InteractionCourseId_OnlineClassID.OnlineClassID, course_info.courseid, course_info.chiefTeacherName, course_info.coursetitle);
            console.log('推送题目结果' + PushTopicResult);
            if (PushTopicResult.errorcode == 0) {
                PushSendSubjectID({
                    type: 'PushSendSubjectID',
                    payload: {
                        //题目推送号
                        SendSubjectID: PushTopicResult.SendSubjectID,
                    }
                });
                Alert.alert('温馨提醒:', '发布题目成功');
                this.setState({ questionStatus: 'open' });
                this.setState({ questionButton: '结束答题' });
                //定时拉取答题结果 SendSubjectID
                console.log('will定时器');
                console.log(' PushTopicResult.SendSubjectID' + PushTopicResult.SendSubjectID);
               // DeviceEventEmitter.emit('icon_color', subject_course.subjectId);
              
                this.timer = setInterval(() => { this.fetch_getSubjectStatistic(); }, 5000);
                
            } else {
                Alert.alert('温馨提醒:', '发布题目失败');
            }
        }
        else {
            let message=[{subjectId:subject_course.subjectId,menu_id:subject_course.menu_id}] 
            DeviceEventEmitter.emit('pushed_icon_color', message);
            let closeSubject = await Interaction.closeSubject(InteractionCourseId_OnlineClassID.OnlineClassID, subject_course.subjectId);
            console.log('关闭答题' + closeSubject.errorCode);
            if (closeSubject.errorCode == 0) {
                this.setState({ questionStatus: 'close' });
                this.setState({ questionButton: '发布题目' });
                Alert.alert('温馨提醒:', '关闭答题成功');
                this.timer && clearInterval(this.timer);
            } else {
                Alert.alert('温馨提醒:', '结束答题失败');
            }
        }
    }

    // 公布正确答案三步走：获取答案-关闭答题-公布答案 
    async publicRightAnswer() {
        const { subject } = this.props;
        const { subject_course } = this.props;
        const { InteractionCourseId_OnlineClassID } = this.props;
        const { course_info } = this.props;

        let subjectId;
        if (this.props.navigation.state.params.type == 'course') {
            console.log('课程-交互');
            subjectId = subject_course.subjectId;
        }
        else {
            console.log('发现-交互');
            subjectId = subject.subjectId;
        }
        if (this.state.questionButton == '发布题目') {
            Alert.alert('温馨提醒:', '题目未开启');
        } else {
            const { GetSendSubjectID } = this.props;
            console.log('公布答案GetSendSubjectID：' + GetSendSubjectID.SendSubjectID);
            let Interaction = new interaction();
            let publicRightAnswer = await Interaction.publicRightAnswer(GetSendSubjectID.SendSubjectID, this.state.correctAnswer, InteractionCourseId_OnlineClassID.OnlineClassID, course_info.courseid);
            if (publicRightAnswer.errorCode == 0) {
                Alert.alert('温馨提醒:', '公布成功');
            } else {
                Alert.alert('温馨提醒:', '题目未开启');
            }

        }


    }
    //答题详情
    async fetch_getSubjectStatistic() {
        const { subject } = this.props;
        const { subject_course } = this.props;
        const { GetSendSubjectID } = this.props;
        let subjectId;
        let subjectTitle;
        if (this.props.navigation.state.params.type == 'course') {
            console.log('课程-交互答题详情');
            subjectId = subject_course.subjectId;
            subjectTitle = subject_course.subjectTitle;
            console.log('课程-交互' + subjectId);

        }
        else {
            console.log('发现-交互');
            subjectId = subject.subjectId;
            subjectTitle = subject.subjectTitle;
            console.log('发现-交互' + subjectId);
        }
        let Interaction = new interaction();
        let SubjectStatistic = await Interaction.getSubjectStatistics(GetSendSubjectID.SendSubjectID, subjectId);
        let optionTitleArray = []
        let optionNumArray = []
        SubjectStatistic.forEach((item) => {
            optionTitleArray.push(item.optionTitle);
            optionNumArray.push(item.optionNum);
        });
         console.log('optionTitleArray' + optionTitleArray);
         console.log('optionNumArray' + optionNumArray);
        this.setState({
            optionTitle: optionTitleArray,
            optionNum: optionNumArray,
        });
    }

}
const styles = StyleSheet.create({
    button_default: {
        marginTop: 40,
        width: width / 4,
        height: 30,
        alignSelf: 'center',
        backgroundColor: '#F0AD4E',
    },
    Content: {
        marginTop: 15,
        backgroundColor: 'white',
    },

    ListItem: {
        paddingLeft: 60,
        height: 40,
    },
    text_style: {
        //fontFamily:'微软雅黑',
        fontSize: 15,
        color: '#353535',
        // paddingLeft:15,
    },
    view: {
        marginTop: 15,
        backgroundColor: 'white',
        borderBottomWidth: 0.2,
        borderBottomColor: "#cac0c0",
    },
    flexbox: {
        marginTop: 15,
        flex: 1,
        flexDirection: 'row',
        justifyContent: 'space-around',
        alignItems: 'center',
        
        
    },
});
function mapStateToProps(state) {
    return {
        subject: state.intercation_question.subject,
        subject_course: state.intercation_question_course.subject_course,
        course_info: state.course_info.course_info,
        InteractionCourseId_OnlineClassID: state.courseInteract_Get_InteractionCourseId_OnlineClassID.InteractionCourseId_OnlineClassID,
        GetSendSubjectID: state.courseInteract_teacherGet_SendSubjectID.SendSubjectID,

    }
}

function mapDispatchToProps(dispatch) {
    return {
        PushSendSubjectID: (state) => dispatch(state),
    }
}

const QuestionTeacher = connect(
    mapStateToProps,
    mapDispatchToProps
)(question_teacher)

export default QuestionTeacher;
